package com.tian.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.tian.mapper.UserMapper;
import com.tian.pojo.User;
import com.tian.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    /*
     * 实现用户登录操作
     * 1.将明文转化为秘闻MD5加密
     * 2.通过username和password查询数据库
     * 3.如果有数据:用户名和密码正确 返回UUID
     *   没有数据:用户名和密码错误 不返回token 返回null
     * */

    public String login(User user) {
        String password = user.getPassword();
        //md5hash相对于md5更加"安全"
        byte[] bytes = password.getBytes();
        String md5Pass = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5Pass);
        //根据其中不为bull的数据当做where条件 u/p
        //Sql:select * from user where u=#{u} and p=#{p}
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
//                queryWrapper.eq("username", user.getUsername())
//                   .eq("password", md5Pass);
        User userDB = userMapper.selectOne(queryWrapper);
        if(userDB == null){
            //没有查询到数据
            return null;
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        return token;
    }

    /**
     * Sql: select * from user limit 数据起始位置,你查询的条数
     * 查询第一页 每页20条:
     *      select * from user limit 0,20
     * 查询第二页 每页20条:
     *      select * from user limit 20,20
     * 查询第三页 每页20条:
     *      select * from user limit 40,20
     * 查询第n页 每页20条:
     *      select * from user limit 20(n-1),20
     *  带查询条件的Sql:
     *      select * from user where name = like "%#{query}%" limit 20(n-1),20
     * @param pageResult
     * @return
     *
     * 关于分页查询的说明
     *      userMapper.selectPage()
     */
    public PageResult getUserList(PageResult pageResult) {
        //1.定义分页对象
        IPage page = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        //构建查询的条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //根据判断条件决定是否拼接where条件
        queryWrapper.like(StringUtils.hasLength(pageResult.getQuery()),"username", pageResult.getQuery());
        //MP提供的分页查询方法,返回值是Page分页对象 其中包含分页的数据结果信息
        page = userMapper.selectPage(page,queryWrapper);
        long total = page.getTotal();
        List records = page.getRecords();
        return pageResult.setRows(records).setTotal(total);
    }
    //user: {id:xxx,status:true/false}

    public void updateStatus(User user) {
        userMapper.updateById(user);

    }


    public String deleteUserById(Integer id) {
        if(id == 1){
            return "no";
        }
        userMapper.deleteById(id);
        return "ok";
    }

    @Transactional
    public void addUser(User user) {
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass);
        user.setStatus(true);   //设定默认值
        userMapper.insert(user);
    }


    public User getById(Integer id) {

        User user = userMapper.selectById(id);
        user.setPassword("");
        return user;
    }


    public String updateUser(User user) {
        User user1 = userMapper.selectById(user.getId());
        String password = user1.getPassword();
        String password1 = user.getPassword();
        String newpassword = user.getNewpassword();
        String md5Pass = DigestUtils.md5DigestAsHex(password1.getBytes());
        if(md5Pass.equals(password)){
            if( StringUtils.isEmpty(newpassword)){
                userMapper.updateById(user);
                return "ok";
            }
            String md5Pass1 = DigestUtils.md5DigestAsHex(user.getNewpassword().getBytes());
            if(md5Pass1.equals(password)){
                return "no1";
            }
            user.setPassword(md5Pass1);
            userMapper.updateById(user);
            return "ok";
        }
        return "no";

    }

    @Override
    public String getAuthById(User user) {
        User admin = userMapper.selectById(1);
        String username = user.getUsername();
        String userpwd = user.getPassword();
        String md5Pass = DigestUtils.md5DigestAsHex(userpwd.getBytes());
        String adminname = admin.getUsername();
        String adminpwd = admin.getPassword();

        if(username.equals(adminname) && md5Pass.equals(adminpwd)){
            return "ok";
        }
        return "no";
    }
}
